package com.zrkizzy.seckill.service.core.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrkizzy.seckill.entity.SeckillOrder;
import com.zrkizzy.seckill.entity.User;
import com.zrkizzy.seckill.mapper.SeckillOrderMapper;
import com.zrkizzy.seckill.service.core.ISeckillOrderService;
import com.zrkizzy.seckill.service.tool.IRedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.zrkizzy.seckill.constant.RedisConst.IS_STOCK_EMPTY;

/**
 * <p>
 * 秒杀订单表 服务实现类
 * </p>
 *
 * @author zhangrongkang
 * @since 2023-03-22
 */
@Service
@Slf4j
public class SeckillOrderServiceImpl extends ServiceImpl<SeckillOrderMapper, SeckillOrder> implements ISeckillOrderService {
    @Autowired
    private IRedisService redisService;

    @Autowired
    private SeckillOrderMapper seckillOrderMapper;

    /**
     * 获取秒杀结果
     *
     * @param user    用户
     * @param goodsId 商品ID
     * @return 存在订单ID：成功； -1：秒杀失败； 0：排队中
     */
    @Override
    public Long getResult(User user, Long goodsId) {
        // 查询秒杀订单
        SeckillOrder seckillOrder = seckillOrderMapper.selectOne(new QueryWrapper<SeckillOrder>()
                .eq("user_id", user.getId())
                .eq("goods_id", goodsId));
        // 如果存在则直接将订单ID进行返回
        if (null != seckillOrder) {
            return seckillOrder.getOrderId();
        }
        log.info("---------------------- 完成获取秒杀结果 ----------------------");
        // 根据Redis中库存数量是否为空返回对应结果
        return redisService.hasKey(IS_STOCK_EMPTY + goodsId) ? -1L : 0L;
    }
}
